import cStringIO, time

def cool_and_topological_vtk(mdpfile,local):
    command=os.path.join(request.folder,'private/development/Libraries/cool_and_topological.exe')
    if local:
        command=command+' '+mdpfile
    else:
        command=command+' '+locate_file(mdpfile)
    print command
    logging.info(command)
    os.system(command)
    vtkfile = mdpfile + ".topological_charge_20.vtk"
    vtkdata=open(locate_file(vtkfile),'rb').read()
    for postfix in [".topological_charge_20.vtk",".cooled20",
                    ".topological_charge_20.sum.vtk",".topological_charge_20.flat.vtk"]:
        os.unlink(locate_file(mdpfile+postfix))
    logging.info('done!')
    return cStringIO.StringIO(vtkdata)

def polyakov_line_vtk(mdpfile,local):
    command=os.path.join(request.folder,'private/development/Libraries/polyakov.exe')
    if local:
        command=command+' '+mdpfile
    else:
        command=command+' '+locate_file(mdpfile)
    print command
    logging.info(command)
    os.system(command)
    vtkfile = mdpfile + ".real_polyakov_line.vtk"
    vtkdata=open(locate_file(vtkfile),'rb').read()
    for postfix in [".real_polyakov_line.vtk",
                    ".imag_polyakov_line.vtk"]:
        os.unlink(locate_file(mdpfile+postfix))
    logging.info('done!')
    return cStringIO.StringIO(vtkdata)
                  
def algorithm(id=None):
    if id is None:
        raise Exception('id is required')
    row = db(db.processedfile.id == id).select().first()
    if row is None:
        raise Exception('no row found with id %s.' % id)

    if row.status!=QUEUED:
        return

    configfile = row.configfile
    while configfile.status==PROCESSING:
        time.sleep(60)
        row = db(db.processedfile.id == id).select().first()
        configfile = row.configfile
    if not configfile.status==COMPLETED:
        return
    logging.info('processing processedfile #%s.' % id)
    try:
        row.update_record(status = PROCESSING)
        db.commit()
        mdpfile = configfile.converted_file
        if row.algorithm == 'topological_charge':
            vtkdata = cool_and_topological_vtk(mdpfile,configfile.localmdp)
        elif row.algorithm == 'polyakov':
            vtkdata = polyakov_line_vtk(mdpfile,configfile.localmdp)
        if configfile.localmdp: mdpfile=mdpfile.split('/')[-1]
        row.update_record(vtkfile=db.processedfile.vtkfile.store(vtkdata,mdpfile+'.vtk'),
                          status=COMPLETED,
                          completed_processing_on=datetime.datetime.today())
        db.commit()
    except Exception,e:
        logging.error('error processedfile #%s %s' % (id, e))
        row.update_record(status=FAILED)
        db.commit()

"""
def algorithm(id=None):
    if id is None:
        raise Exception('id is required')
    row = db(db.processedfile.id == id).select().first()
    if row is None:
        raise Exception('no row found with id %s.' % id)
    configfile = row.configfile
    if row.status!=QUEUED or not configfile.status==COMPLETED:
        return
    logging.info('processing processedfile #%s.' % id)
    try:
        row.update_record(status = PROCESSING)
        db.commit()
        mdpfile = configfile.converted_file
        if row.algorithm == 'topological_charge':
            vtkdata = cool_and_topological_vtk(mdpfile)
        elif row.algorithm == 'polyakov':
            vtkdata = polyakov_line_vtk(mdpfile)
        row.update_record(vtkfile=db.processedfile.vtkfile.store(vtkdata,mdpfile+'.vtk'),
                          status=COMPLETED,
                          completed_processing_on=datetime.datetime.today())
        db.commit()
    except Exception,e:
        logging.error('error processedfile #%s %s' % (id, e))
        row.update_record(status=FAILED)
        db.commit()
"""


id = int(sys.argv[-1])
algorithm(id)

